import {GameModel, isMap, mainCtx, MoveableModel} from "./core.ts";
import {TankImage} from "./const.ts";
import {Bomb} from "./bomb.ts";
import {isTank, Tank} from "./Tank.ts";
import {GameMap} from "./GameMap.ts";

const bulletImagePos = {
    right: [345, 100.5, 6, 6],
    left: [329, 100.5, 6, 6],
    top: [321.5, 101, 6, 6],
    bottom: [337.5, 101, 6, 6]
} as { [key: string]: number[] };


export class Bullet extends MoveableModel {
    direction = 'top'
    moving = true
    state = 0
    compactLevel = 2
    tank: Tank
    camp: number

    constructor(x: number, y: number, direction: string, tank: Tank) {
        super(x, y, 6, 6, mainCtx);
        this.direction = direction
        this.speed = 5
        this.tank = tank
        this.camp = tank.camp
    }

    render(): void {
        if (this.state === 0) {
            let imgPos = bulletImagePos[this.direction]
            this.ctx.drawImage(TankImage, imgPos[0], imgPos[1], imgPos[2], imgPos[3], this.x - 3, this.y - 3, 6, 6)
        }

    }

    update(time: number): void {
        super.update(time)
    }

    compact(model: GameModel | GameMap): void {
        if (isMap(model)) {
            this.destroy()
            new Bomb(this.x, this.y).reg()
        } else if (isTank(model) && this.camp !== model.camp) {
            this.destroy()
            model.destroy()
            new Bomb(this.x, this.y).reg()
        } else if (isBullet(model) && this.camp !== model.camp) {
            this.destroy()
            model.destroy()
            new Bomb(this.x, this.y).reg()
        }

    }

    destroy() {
        super.destroy();
        this.tank.bullets --
    }
}

export function isBullet(model: any): model is Bullet {
    return model instanceof Bullet
}